<?php
function MSG($text,$url = '',$status = ''){
	message($text,$url,$status);
}
function resp($data){
	die(json_encode($data,JSON_UNESCAPED_UNICODE));
}
function tb($name){
	return tablename('junsion_listenbook_'.$name);
}
function update($name,$arr = '',$arr2 = ''){
	return pdo_update('junsion_listenbook_'.$name,$arr,$arr2);
}
function insert($name,$arr = ''){
	return pdo_insert('junsion_listenbook_'.$name,$arr);
}
function del($name,$arr = '',$op = 'and'){
	return pdo_delete('junsion_listenbook_'.$name,$arr,$op);
}
function get($sql){
	return pdo_fetch($sql);
}
function col($sql){
	return pdo_fetchcolumn($sql);
}
function getall($sql,$col = ''){
	if ($col) return pdo_fetchall($sql,array(),$col);
	return pdo_fetchall($sql);
}
function imgtobase64($url){
	load()->func('communication');
	$result = ihttp_get($url);
	$file_content = chunk_split(base64_encode($result['content'])); // base64编码
	$file_content = str_replace("\r\n", '', $file_content);
	$img_type = 'png';
	$img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;
	return $img_base64;
}
function updateMemScore($params){
	if($params['score']==0) return 1;
	$data = array(
			'mid' => $params['mid'],
			'score' => $params['score'],
			'remark' => $params['remark'],
			'createtime' => time()
	);
	insert('score_log', $data);
	$set = " set score = score + '{$params['score']}' ";
	pdo_query('update '.tb("mem")." {$set} where id='{$params['mid']}'");
	return 1;
}
function updateMemCredit($params){
	if($params['credit']==0) return 0;
	$data = array(
			'mid' => $params['mid'],
			'aid' => $params['aid'],
			'credit' => $params['credit'],
			'remark' => $params['remark'],
			'createtime' => time()
	);
	insert('mcredit', $data);
	$set = " set credit = credit + '{$params['credit']}' ";
	if($params['credit']>0) $set .= " , total_credit = total_credit + '{$params['credit']}' ";
	pdo_query('update '.tablename("junsion_listenbook_mem")." {$set} where id='{$params['mid']}'");
	return 1;
}
function WXLimit(){
	$userAgent = $_SERVER['HTTP_USER_AGENT'];
	if (!strpos($userAgent, 'MicroMessenger')) {
		die('
			<html>
			<head>
			<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
			<meta name="viewport"
				content="width=device-width, initial-scale=1, user-scalable=0">
			<title>抱歉，出错了</title>
			<meta charset="utf-8">
			<meta name="viewport"
				content="width=device-width, initial-scale=1, user-scalable=0">
			<link rel="stylesheet" type="text/css"
				href="https://res.wx.qq.com/connect/zh_CN/htmledition/style/wap_err1a9853.css">
			</head>
			<body>
				<div class="page_msg">
					<div class="inner">
						<span class="msg_icon_wrp"><i class="icon80_smile"></i></span>
						<div class="msg_content">
							<h4>请在微信客户端打开链接</h4>
						</div>
					</div>
				</div>

			</body>
			</html>
			');
	}
}

function sendPaySucMsg($order, $book=''){
	global $_W;
	if(empty($book)) $book = get('select id,uniacid,title,start_day from ' .tb('book'). " where id = '{$order['bid']}'");
	$replaceArr = [
			'#课程#' => $book['title'],
			'#金额#' => $order['price'],
			'#时间#' => date('Y-m-d H:i:s'),
			'#开课#' => date('Y-m-d',getNextWeekDate($book['start_day'])),
	];
	$mem = get('select id,openid from ' .tb('mem'). " where id = '{$order['mid']}'");
	$modules = pdo_fetch('select * from '.tablename('uni_account_modules')." where uniacid='{$_W['uniacid']}' and module='junsion_listenbook'");
	$cfg = unserialize($modules['settings']);
	$postData = getTplMsgData($cfg['tpmsg_pay'],$replaceArr);
	$res = 0;
	$url = $_W['siteroot'].'app/index.php?i='.$_W['uniacid'].'&c=entry&do=index&m=junsion_listenbook';
	if(!empty($cfg['custom_pay_msg'])){
		foreach ($replaceArr as $k => $v){
			$cfg['custom_pay_msg'] = str_replace($k, $v, $cfg['custom_pay_msg']);
		}
		if(strstr($cfg['custom_pay_msg'], ';')){
			$custom_pay_msg = explode(';', $cfg['custom_pay_msg']);
			foreach ($custom_pay_msg as $k => $v){
				$val = explode('|', $v);
				$custom_pay_msg[$k+1] = [
						'title' => $val[0],
						'value' => $val[1],
				];
			}
		}
		else{
			$custom_pay_msg = $cfg['custom_pay_msg'];
		}
		$res = sendCustomNotice($book['uniacid'],$mem['openid'], $custom_pay_msg);
	}
	if($res !=1){
		$account = getAccount();
		$result = $account->sendTplNotice($mem['openid'], $cfg['tpmsg_pay']['msgid'], $postData, $url);
	}
	return 1;
}

function getNextWeekDate($week){
	$w = date('w');
	if($w==$week){
		$time = time();
	}else if ($week>$w){
		$d = $week - $w;
		$time = strtotime('+'.$d.'day');
	}else{
		$d = 7 - $w + $week;
		$time = strtotime('+'.$d.'day');
	}
	return strtotime(date('Y-m-d',$time));
}

function sendListenMsg($wids, $book, $mem, $cfg, $url){
	$replaceArr = [
			'#课程#' => $book['title'],
			'#时间#' => date('Y-m-d H:i:s'),
	];
	$postData = getTplMsgData($cfg['tpmsg_listen'],$replaceArr);
	$res = 0;
	if ($wids && $mem['unionid']) $mem_infos = pdo_fetchall('select uniacid,unionid,openid from ' .tablename('mc_mapping_fans'). " where unionid = '{$mem['unionid']}' and uniacid in (".implode(',', $wids).")");
	else $mem_infos[] = $mem;
	if(!empty($cfg['custom_msg'])){
		foreach ($replaceArr as $k => $v){
			$cfg['custom_msg'] = str_replace($k, $v, $cfg['custom_msg']);
		}
		if(strstr($cfg['custom_msg'], ';')){
			$custom_msg = explode(';', $cfg['custom_msg']);
			foreach ($custom_msg as $k => $v){
				$val = explode('|', $v);
				$custom_msg[$k+1] = [
						'title' => $val[0],
						'value' => $val[1],
				];
			}
			$custom_msg[0] = '';
		}
		else{
			$custom_msg = $cfg['custom_msg'];
		}
		$res = reSendCustomMsg($mem_infos, ['msg'=>$custom_msg, 'remark'=>$postData['remark']['value'], 'url'=>$url]);
		return $res;
	}
	if($res !=1){
		reSendTplMsg($mem_infos, ['msgid'=>$cfg['tpmsg_listen']['msgid'], 'data'=>$postData, 'url'=>$url], 0);
	}
	return 1;
}
function reSendCustomMsg($mem_infos, $data, $index=0){
	if(empty($mem_infos[$index])) return 0;
	$res = sendCustomNotice($mem_infos[$index]['uniacid'], $mem_infos[$index]['openid'], $data['msg'], $data['remark'], $data['url']);
	if($res==1) return 1;
	else return reSendCustomMsg($mem_infos, $data, ++$index);
}
function reSendTplMsg($mem_infos, $data, $index=0){
	if(empty($mem_infos[$index])) return 0;
	$account = getAccount($mem_infos[$index]['uniacid']);
	$result = $account->sendTplNotice($mem_infos[$index]['openid'], $data['msgid'], $data['data'], $data['url']);
	if($result==1) return 1;
	else return reSendTplMsg($mem_infos, $data, ++$index);
}
function getTplMsgData($msg, $replaceArr){
	foreach ($replaceArr as $k => $v){
		if(strstr($msg['title'], $k)) $msg['title'] = str_replace($k, $v, $msg['title']);
		if(strstr($msg['remark'], $k)) $msg['remark'] = str_replace($k, $v, $msg['remark']);
	}
	$postdata = [
			'first' => [
					'value' => $msg['title'],
					'color' => $msg['titlecolor'],
			],
			'remark' => [
					'value' => $msg['remark'],
					'color' => $msg['remarkcolor'],
			],
	];
	$i = 0;
	foreach ($msg['value'] as $k => $value) {
		if (empty($value)) continue;
		$i++;
		foreach ($replaceArr as $kr => $vr){
			if(strstr($value, $kr)) $value = str_replace($kr, $vr, $value);
		}
		$postdata['keyword'.$i] = [
				'value' => $value,
				'color' => $msg['valuecolor'][$k]
		];
	}
	return $postdata;
}

function sendCustomNotice($wid, $openid, $msg, $remark, $url = ''){
	if (empty($openid)) return ;
	$account = getAccount($wid);
	if (!($account)) return ;
	$content = '';
	if (is_array($msg)){
		foreach ($msg as $key => $value ){
			if($key == 'remark' || $key==0) continue;
			if (!(empty($value['title']))){
				$content .= $value['title'] . ':' . $value['value'] . "\n";
			}
			else{
				$content .= $value['value'] . "\n";
			}
		}
	}else{
		$content = $msg."\n";
	}
	if (!(empty($url))) $content .= "<a href='" . $url . "'>".$remark."</a>";
	$post = array( 'touser' => $openid, 'msgtype' => 'text', 'text' => array('content' => urlencode($content)));
	$res = $account->sendCustomNotice($post);
	file_put_contents(IA_ROOT."/addons/junsion_listenbook/msgres", date('Y-m-d H:i:s')." post:".json_encode($post)."\nres:".json_encode($res,JSON_UNESCAPED_UNICODE)."\n",FILE_APPEND);
	return $res;
}

function getAccount($weid=0)
{
	global $_W;
	if(empty($weid)) $weid = $_W['acid'];
	load()->model('account');
	if (!(empty($weid))) {
		return WeAccount::create($weid);
	}
	$acid = pdo_fetchcolumn('SELECT acid FROM ' . tablename('account_wechats') . ' WHERE `uniacid`=:uniacid LIMIT 1', array(':uniacid' => $weid));
	return WeAccount::create($acid);
}

function substr_cut($user_name){
	//获取字符串长度
	$strlen = mb_strlen($user_name, 'utf-8');
	//如果字符创长度小于2，不做任何处理
	if($strlen<2){
		return $user_name;
	}else{
		//mb_substr — 获取字符串的部分
		$firstStr = mb_substr($user_name, 0, 1, 'utf-8');
		$lastStr = mb_substr($user_name, -1, 1, 'utf-8');
		//str_repeat — 重复一个字符串
		return $strlen == 2 ? (mb_substr($user_name, 0, 1, 'utf-8')."*"): ($firstStr . str_repeat("*", min($strlen - 2,2)) . $lastStr);
	}
}

/*
 * field string  参数名
 * con array 各内容的注释，用于提醒用户 设置  变量;格式如： array('title'=>'标题内容：#昵称#代表用户昵称','keyword'=>'键值内容： #时间#代表当前时间','remark'=>'备注内容')
 * needurl 是否需要自定义链接；若需要 data参数需要带上url
 * needminpro 是否需要自定义跳转小程序；若需要 data参数需要带上appid和path
 * data array 默认参数值数组 格式: array('msgid'=>'模板消息ID','title'=>'头部标题','titlecolor'=>'头部标题颜色','value'=>array('keyword1内容','keyword2内容'),'valuecolor'=>array('keyword1内容颜色','keyword2内容颜色'),'remark'=>'尾部描述内容','remarkcolor'=>'尾部描述内容颜色','url'=>'跳转链接','appid'=>'跳转小程序appid','path'=>'跳转小程序路径')
 * */
function getTempDiv($field,$con,$needurl = false,$needminpro = false,$data){
	$modalid = 'tempDiv_'.random(10);
	if($con['title']) $con['title'] = "<span class='help-block'>对填充模板 {{first.DATA}} 的值；{$con['title']}</span>";

	$tempdiv = "
	<div class='form-group'>
	<label class='col-xs-12 col-sm-3 col-md-2 control-label'>模版消息ID</label>
	<div class='col-xs-12 col-sm-9'>
	<input type='text' name='{$field}[msgid]' value='{$data[msgid]}' class='form-control' placeholder='如：fCfGChknZxAVu2Ev_ZADMxZq553EdHvKSefMjQ36J_8' >
	</div>
	</div>

	<div class='form-group'>
	<label class='col-sm-2 control-label must'>头部标题</label>
	<div class='col-sm-9 title' style='padding-right:0'>
	<textarea name='{$field}[title]' class='form-control' placeholder='{{first.DATA}}'>{$data[title]}</textarea>
	{$con['title']}
	</div>
	<div class='col-sm-1' style='padding-left:0;'>
	<input type='color' name='{$field}[titlecolor]' value='{$data[titlecolor]}' style='width:32px;height:32px;'>
	</div>
	</div>

	<!--增加ADD-->
	<div id='type-items'>
	<div class='form-group'  id='{$modalid}' style='display: none;'>
	<div class='form-group key_item'>
	<label class='col-sm-2 control-label'>keyword.DATA</label>
	<div class='col-sm-7' style='padding:0;padding-left:15px;'>
	<textarea name='{$field}[value][]' class='form-control' placeholder='{{keyword.DATA}}'></textarea>
	</div>
	<div class='col-sm-1' style='padding:0'>
	<input type='color' name='{$field}[valuecolor][]' value='' style='width:32px;height:32px;'>
	</div>
	<a class='btn btn-default' href='javascript:;' onclick='$(this).closest(\".key_item\").remove()'><i class='fa fa-remove'></i> 删除</a>
	</div>
	</div>
	</div>
	<!--ADD结束-->

	<div class='form-group'>
	";
	foreach ($data['value'] as $k => $value) {
		if ($value){
			$tempdiv .= "
			<div class='form-group key_item'>
			<label class='col-sm-2 control-label'>keyword.DATA</label>
			<div class='col-sm-7' style='padding:0;padding-left:15px;'>
			<textarea name='{$field}[value][]' class='form-control' placeholder='{{keyword.DATA}}'>{$value}</textarea>
			</div>
			<div class='col-sm-1' style='padding:0'>
			<input type='color' name='{$field}[valuecolor][]' value='{$data['valuecolor'][$k]}' style='width:32px;height:32px;'>
			</div>
			<a class='btn btn-default' href='javascript:;' onclick='$(this).closest(\".key_item\").remove()'><i class='fa fa-remove'></i> 删除</a>
			</div>
			";
		}
	}
	if ($con['keyword']) $con['keyword'] = "<span class='help-block'>{$con['keyword']}</span>";
	if ($con['remark']) $con['remark'] = "<span class='help-block'>填充模板 {{remark.DATA}} 的值；{$con['remark']}</span>";
	$tempdiv .= "
	</div>
	<div class='form-group'>
	<label class='col-sm-2 control-label'></label>
	<div class='col-sm-9 col-xs-12'>
	<a class='btn btn-default btn-add-type' onclick='onAdd_{$modalid}(this)'><i class='fa fa-plus' title=''></i> 增加一条键</a>
	{$con['keyword']}
	</div>
	</div>
	<div class='form-group'>
	<label class='col-sm-2 control-label'>尾部描述</label>
	<div class='col-sm-9 title' style='padding-right:0'>
	<textarea name='{$field}[remark]' class='form-control' placeholder='{{remark.DATA}}'>{$data[remark]}</textarea>
	{$con['remark']}
	</div>
	<div class='col-sm-1' style='padding-left:0'>
	<input type='color' name='{$field}[remarkcolor]' value='{$data[remarkcolor]}' style='width:32px;height:32px;'>
	</div>
	</div>
	";
	if ($needurl)
		$tempdiv .= "
		<div class='form-group'>
		<label class='col-xs-12 col-sm-3 col-md-2 control-label'>任务中点击链接</label>
		<div class='col-xs-12 col-sm-9'>
		<input type='text' name='{$field}[url]' value='{$data[url]}' class='form-control' placeholder='http://' >
		</div>
		</div>
		";
		if ($needminpro)
			$tempdiv .= "
			<div class='form-group'>
			<label class='col-xs-12 col-sm-3 col-md-2 control-label'>小程序appid</label>
			<div class='col-xs-12 col-sm-9'>
			<input type='text' name='{$field}[appid]' value='{$data[appid]}' class='form-control' >
			</div>
			</div>
			<div class='form-group'>
			<label class='col-xs-12 col-sm-3 col-md-2 control-label'>小程序路径</label>
			<div class='col-xs-12 col-sm-9'>
			<input type='text' name='{$field}[path]' value='{$data[path]}' class='form-control' >
			</div>
			</div>
			";
			$tempdiv .= "
			<script>
			function onAdd_{$modalid}(obj){
			$(obj).parent().parent().before('<div class=\"type-items\">'+$('#{$modalid}').html()+'</div>');
}
</script>
";
			echo $tempdiv;
}

function getImgBase64($url){
	load()->func('communication');
	$result = ihttp_get($url);
	$file_content = chunk_split(base64_encode($result['content'])); // base64编码
	$file_content = str_replace("\r\n", '', $file_content);
	$img_type = 'png';
	$img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;
	return $img_base64;
}